package org.seckill.web;

import org.seckill.dto.Exposer;
import org.seckill.dto.SeckillExecution;
import org.seckill.dto.SeckillResult;
import org.seckill.entity.Seckill;
import org.seckill.enums.SeckillStatuEnum;
import org.seckill.exception.RepeatKillException;
import org.seckill.exception.SeckillCloseException;
import org.seckill.service.SeckillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * Created by Jungle on 2016/11/9.
 */
@Controller //注解：标识当前类为springmvc中的控制器
@RequestMapping("/seckill") // url:/模块/资源/{id}/细分   /seckill/list
public class SeckillController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 引入服务层，通过注解的形式进行注入
    @Autowired
    private SeckillService seckillService;

    @RequestMapping(value="/list",method = RequestMethod.GET)
    public String list(Model model){
        logger.debug("l------------------controller is commint in ");
        // 获取列表页
        // list.jsp + model = ModelAndView
        List<Seckill> list = seckillService.getSeckillList();
        model.addAttribute("list",list);
        return "list"; // 此处实际路径为：WEB-INF/jsp/list.jsp
    }

    /**
     * 查看秒杀详情
     * 说明：
     * 1、PathVariable 用来标识参数，也可以理解为设置别名
     * @param model
     * @return
     */
    @RequestMapping(value = "/{seckillId}/detail", method = RequestMethod.GET)
    public String detail(@PathVariable("seckillId") Long seckillId , Model model) {

        if(seckillId == null){
            // 重新重定向请求，请求转发到上面列表函数中
            return "redirect:/seckill/list";
        }
        Seckill seckill = seckillService.getById(seckillId);
        if(null == seckill){
            return "forward:/seckill/list";
        }
        model.addAttribute("seckill", seckill);
        return "detail";
    }

    // ============================ AJAX 接口 ， json格式的交互 ===========================

    /**
     * 暴露秒杀地址
     * 1、此接口为为ajax + json 的请求惭怍
     * @param seckillId
     * @return
     */
    @RequestMapping(value = "/{seckillId}/exporse",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody // 标识响应内容在返回body中
    public SeckillResult<Exposer> exposer(Long seckillId){
        SeckillResult<Exposer> result = null;
        try {
            Exposer exposer = seckillService.exportSeckillUrl(seckillId);
            result =  new SeckillResult<Exposer>(true, exposer);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            result = new SeckillResult<Exposer>(false, e.getMessage());
        }
        return result;
    }

    /**
     * 执行秒杀接口
     * 1、用户执行的手机号是从Cookie中获取的，标识中的require设置为false为程序处理空异常
     * @return
     */
    @RequestMapping(value = "/{seckillId}/{md5}/execution",
            method = RequestMethod.POST,
            produces = "application/json;charset=UTF-8")
    @ResponseBody
    public SeckillResult<SeckillExecution> execute(@PathVariable("seckillId") Long seckillId,
                                                   @PathVariable("md5") String md5,
                                                   @CookieValue(value = "killPhone",required = false) Long userPhone){
        SeckillResult<SeckillExecution> result ;
        if(null == userPhone){
            return new SeckillResult<SeckillExecution>(false, "未注册");
        }
        try {
            SeckillExecution seckillExecution = seckillService.executeSeckill(seckillId, userPhone, md5);
            return new SeckillResult<SeckillExecution>(true, seckillExecution);
        }catch(RepeatKillException e){
            // 重复秒杀异常
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatuEnum.REPEAT_KILL);
            return new SeckillResult<SeckillExecution>(false, seckillExecution);
        }catch(SeckillCloseException e){
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatuEnum.END);
            return new SeckillResult<SeckillExecution>(false, seckillExecution);
        }catch(Exception e){
            logger.error(e.getMessage(),e);
            SeckillExecution seckillExecution = new SeckillExecution(seckillId, SeckillStatuEnum.INNER_ERROR);
            return new SeckillResult<SeckillExecution>(false, seckillExecution);
        }
    }

    @RequestMapping(value = "/time/now",method = RequestMethod.GET)
    public SeckillResult<Long> time(){
        Date now = new Date();
        return new SeckillResult<Long>(true, now.getTime());
    }

}
